package myky.com.doctorapp.fragment


import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.nukc.stateview.Constant
import com.google.gson.Gson
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.umeng.analytics.MobclickAgent
import kotlinx.android.synthetic.main.fragment_news_sub.*
import myky.com.doctorapp.R
import myky.com.doctorapp.adapter.HomeArticalAdapter
import myky.com.doctorapp.api.Address
import myky.com.doctorapp.entity.HomeArtiCalEntity
import myky.com.doctorapp.entity.HealthEntity
import myky.com.doctorapp.ui.HealthArticalActivity
import myky.com.doctorapp.utils.Constants
import myky.com.doctorapp.utils.OkHttpUtils.OkHttpManager
import myky.com.doctorapp.utils.RecyclerUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.HashMap


/**
 * Title:
 * Description: TODO
 * @author xiangyao
 * date 2019/1/14
 */
class HomeNewsSubFragment: Fragment, OnLoadMoreListener, BaseQuickAdapter.OnItemChildClickListener {

    constructor(){

    }




    lateinit var homeArtiCalEntities: ArrayList<HomeArtiCalEntity>

    private val hasMap = HashMap<String, String>()

    var canLoadMore: Boolean = false

    var mTagId: Int=-1

    lateinit var homeArticalAdapter: HomeArticalAdapter

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun scrollToFirst(message: Message) {
        if (message.what == Constant.SCROLLTOFIST) {
            if (homeArtiCalEntities.size > 0) {
                artcalListView.smoothScrollToPosition(0)

            }
        }
    }


    override fun onHiddenChanged(hidden: Boolean) {
        if (hidden) {
            loadingLayout.visibility = View.VISIBLE
        } else {
            //获取健康学堂列表第一次查看0-9条信息
            getHealthList(mTagId, RecyclerUtils.getSortByFrist(0, 9))
        }
    }

    private fun getHealthList(tagId: Int, params: String) {
        loadingLayout.visibility = View.VISIBLE
        val url = Address.HEALTHLECTUREURL + tagId + "/" + params
        OkHttpManager.getInstance(activity).get(url, object : OkHttpManager.HttpCallBack {
            override fun onFailure(errorMsg: String) {

            }

            override fun onResponse(jsonObject: String, type: Long) {
                if (type == 220L) {
                    homeArtiCalEntities.clear()
                    val gson = Gson()
                    val healthBean = gson.fromJson<HealthEntity>(jsonObject, HealthEntity::class.java)
                    val articleLists = healthBean.payLoad.articleList
                    if (articleLists != null && articleLists.size > 0) {
                        canLoadMore = true
                        homeArticalAdapter.loadMoreComplete()
                        val size = articleLists.size
                        val articleListBean = articleLists.get(0)
                        val homeArtiCalEntityImage = HomeArtiCalEntity()
                        homeArtiCalEntityImage.createtime = articleListBean.createtime
                        homeArtiCalEntityImage.resource = articleListBean.resource
                        homeArtiCalEntityImage.title = articleListBean.title
                        homeArtiCalEntityImage.articleid = articleListBean.articleid
                        homeArtiCalEntityImage.type = HomeArtiCalEntity.IMAGITEM
                        homeArtiCalEntities.add(homeArtiCalEntityImage)
                        if (size > 1) {
                            for (i in 1 until size) {
                                val bean = articleLists.get(i)
                                val homeArtiCalEntityNormal = HomeArtiCalEntity()
                                homeArtiCalEntityNormal.type = HomeArtiCalEntity.NORMALCONTEN
                                homeArtiCalEntityNormal.createtime = bean.createtime
                                homeArtiCalEntityNormal.title = bean.title
                                homeArtiCalEntityNormal.resource = bean.resource
                                homeArtiCalEntityNormal.articleid = bean.articleid
                                homeArtiCalEntities.add(homeArtiCalEntityNormal)
                            }
                        }
                        homeArticalAdapter.loadMoreComplete()
                    } else {
                        homeArticalAdapter.loadMoreComplete()
                    }
                    loadingLayout.postDelayed({
                        if (homeArtiCalEntities.size > 0) {
                            loadingLayout.visibility = View.GONE
                        }
                    }, 500)
                    if (homeArtiCalEntities.size > 0) {
                        artcalListView.smoothScrollToPosition(0)
                    }
                    homeArticalAdapter.notifyDataSetChanged()
                }
            }
        })


    }


    private fun getMoreHealthList(tagId: Int, params: String) {
        val url = Address.HEALTHLECTUREURL + tagId + "/" + params
        OkHttpManager.getInstance(activity).get(url, object : OkHttpManager.HttpCallBack {
            override fun onFailure(errorMsg: String) {

            }

            override fun onResponse(jsonObject: String, type: Long) {
                if (type == 220L) {
                    val gson = Gson()
                    val healthBean = gson.fromJson<HealthEntity>(jsonObject, HealthEntity::class.java)
                    val articleLists = healthBean.payLoad.articleList

                    if (articleLists == null) {
                        homeArticalAdapter.loadMoreEnd()
                    } else {
                        val size = articleLists.size
                        for (i in 0 until size) {
                            val bean = articleLists.get(i)
                            val homeArtiCalEntityNormal = HomeArtiCalEntity()
                            homeArtiCalEntityNormal.type = HomeArtiCalEntity.NORMALCONTEN
                            homeArtiCalEntityNormal.createtime = bean.createtime
                            homeArtiCalEntityNormal.title = bean.title
                            homeArtiCalEntityNormal.resource = bean.resource
                            homeArtiCalEntityNormal.articleid = bean.articleid
                            homeArtiCalEntities.add(homeArtiCalEntityNormal)
                        }
                        homeArticalAdapter.loadMoreComplete()
                    }
                    homeArticalAdapter.notifyDataSetChanged()
                }

            }
        })
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        getMoreHealthList(mTagId, RecyclerUtils.getSortByItem(10))
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

        val data = homeArticalAdapter.data
        val homeArtiCalEntity = data[position]
        hasMap["Title"] = homeArtiCalEntity.title
        MobclickAgent.onEvent(context, "CM_001", hasMap)//友盟统计
        val intent = Intent(context, HealthArticalActivity::class.java)
        intent.putExtra("Articleid", homeArtiCalEntity.articleid)
        activity.startActivity(intent)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val mRootView = inflater.inflate(R.layout.fragment_news_sub, container, false)
        EventBus.getDefault().register(this)

       mTagId= arguments.getInt(Constants.TAGID)

        return mRootView
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        homeArtiCalEntities = ArrayList()
        artcalListView.layoutManager = LinearLayoutManager(activity)
        homeArticalAdapter = HomeArticalAdapter(homeArtiCalEntities)
        artcalListView.adapter = homeArticalAdapter
        homeArticalAdapter.onItemChildClickListener = this

        homeArticalAdapter.setOnLoadMoreListener({
            if (canLoadMore) {
                getMoreHealthList(mTagId, RecyclerUtils.getSortByItem(10))
            }
        }, artcalListView)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

}
